package com.practice.springboot_01_zwj.controller;

import com.practice.springboot_01_zwj.entity.*;
import com.practice.springboot_01_zwj.service.IncomeQuestionService;
import com.practice.springboot_01_zwj.util.ExcelExportUtil;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/api/incomeQuestion")
public class IncomeQuestionController {

    private static final Logger logger = LoggerFactory.getLogger(IncomeQuestionService.class);
    private final IncomeQuestionService incomeQuestionService;

    public IncomeQuestionController(IncomeQuestionService incomeQuestionService) {
        this.incomeQuestionService = incomeQuestionService;
    }

    @PostMapping("/selectIncome")
    public Map<String, Object> selectIncome(@RequestBody IncomeQuestion request) {
        // 参数校验逻辑
        String cityCode = request.getCityCode();
        String provinceCode = request.getProvinceCode();
        String yearFilter = request.getYearFilter(); // 获取年份筛选参数
        // 验证年份筛选参数
        if (yearFilter != null &&
                !Arrays.asList("2023", "2024", "2025", "all").contains(yearFilter)) {
            throw new IllegalArgumentException("yearFilter 必须是 2023, 2024, 2025 或 all");
        }

        if (cityCode != null) {
            return incomeQuestionService.selectIncomeByCityCode(cityCode, yearFilter);
        } else {
            return incomeQuestionService.selectIncomeByProvinceCode(provinceCode, yearFilter);
        }
    }


    @PostMapping("/selectMgr")
    public Map<String, Object> selectMgr(@RequestBody IncomeQuestion request) {
        String cityCode = request.getCityCode();
        String provinceCode = request.getProvinceCode();
        String yearFilter = request.getYearFilter(); // 获取年份筛选参数
        // 验证年份筛选参数
        if (yearFilter != null &&
                !Arrays.asList("2023", "2024", "2025", "all").contains(yearFilter)) {
            throw new IllegalArgumentException("yearFilter 必须是 2023, 2024, 2025 或 all");
        }
        // 参数校验：必须且只能传递一个有效参数
        if ((cityCode == null && provinceCode == null) || (cityCode != null && provinceCode != null)) {
            throw new IllegalArgumentException("必须且只能传递 cityCode 或 provinceCode 中的一个参数");
        }
        if (cityCode != null) {
            return incomeQuestionService.selectMgrByCityCode(cityCode,yearFilter);
        } else {
            return incomeQuestionService.selectMgrByProvinceCode(provinceCode,yearFilter);
        }
    }

    @PostMapping("/selectQuestion")
    public Map<String, Object> selectQuestion(@RequestBody IncomeQuestion request) {
        String cityCode = request.getCityCode();
        String provinceCode = request.getProvinceCode();
        String yearFilter = request.getYearFilter(); // 获取年份筛选参数
        // 验证年份筛选参数
        if (yearFilter != null &&
                !Arrays.asList("2023", "2024", "2025", "all").contains(yearFilter)) {
            throw new IllegalArgumentException("yearFilter 必须是 2023, 2024, 2025 或 all");
        }
        // 参数校验：必须且只能传递一个有效参数
        if ((cityCode == null && provinceCode == null) || (cityCode != null && provinceCode != null)) {
            throw new IllegalArgumentException("必须且只能传递 cityCode 或 provinceCode 中的一个参数");
        }
        if (cityCode != null) {
            return incomeQuestionService.selectQuestionByCityCode(cityCode,yearFilter);
        } else {
            return incomeQuestionService.selectQuestionByProvinceCode(provinceCode,yearFilter);
        }
    }
    @PostMapping("/totalIncome")
    public PageResult<IncomeQuestion> selectIncomeAll(@RequestBody ConditionRequest params) {
        // 1. 参数校验
        validateParams(params.getCityCode(), params.getProvinceCode());

        // 2. 处理条件对象 - 使用ConditionRequest的默认初始化值
        IncomeQuestion condition = params.getCondition();

        // 3. 处理分页参数 - 使用ConditionRequest的默认初始化值
        PageRequest pageRequest = processPageRequest(params.getPageRequest());

        // 4. 路由到服务层
        if (StringUtils.hasText(params.getCityCode())) {
            return incomeQuestionService.selectCityTotalIncomePage(
                    params.getCityCode(),
                    condition,
                    pageRequest
            );
        } else {
            return incomeQuestionService.selectProvinceTotalIncomePage(
                    params.getProvinceCode(),
                    condition,
                    pageRequest
            );
        }
    }

    // 分页参数处理方法
    private PageRequest processPageRequest(PageRequest request) {
        // 使用ConditionRequest的默认值（pageNum=1, pageSize=20）
        // 只需做边界保护
        if (request == null) {
            return new PageRequest(); // 使用默认值
        }

        // 确保页码至少为1
        if (request.getPageNum() == null || request.getPageNum() < 1) {
            request.setPageNum(1);
        }

        // 限制页大小在1-100之间
        if (request.getPageSize() == null || request.getPageSize() < 1) {
            request.setPageSize(20); // 使用默认值
        } else if (request.getPageSize() > 100) {
            request.setPageSize(100); // 最大100条
        }

        return request;
    }

//    @PostMapping("/{operation}")
//    public PageResult<IncomeQuestion> handleRequest(
//            @PathVariable String operation,
//            @RequestBody ConditionRequest params) {
//
//        // 验证参数
//        validateParams(params.getCityCode(), params.getProvinceCode());
//
//        // 处理条件对象
//        IncomeQuestion condition = Optional.ofNullable(params.getCondition())
//                .orElseGet(IncomeQuestion::new);
//
//        // 设置年份筛选参数
////        condition.setYearFilter(params.getYearFilter());
//
//        // 处理分页参数
//        PageRequest pageRequest = processPageRequest(params.getPageRequest());
//
//        // 确定区域类型
//        IncomeQuestionService.AreaType areaType;
//        String areaCode;
//
//        if (StringUtils.hasText(params.getCityCode())) {
//            areaType = IncomeQuestionService.AreaType.CITY;
//            areaCode = params.getCityCode();
//        } else {
//            areaType = IncomeQuestionService.AreaType.PROVINCE;
//            areaCode = params.getProvinceCode();
//        }
//
//        // 调用统一服务方法
//        return incomeQuestionService.selectByOperation(
//                operation.toUpperCase(),
//                areaCode,
//                areaType,
//                condition,
//                pageRequest
//        );
//    }
    @PostMapping("/{operation}")
    public PageResult<IncomeQuestion> handleRequest(
            @PathVariable String operation,
            @RequestBody ConditionRequest params) {

        // 验证参数
        validateParams(params.getCityCode(), params.getProvinceCode());

        // 处理条件对象
        IncomeQuestion condition = Optional.ofNullable(params.getCondition())
                .orElseGet(IncomeQuestion::new);

        // 设置年份筛选参数
//        condition.setYearFilter(params.getYearFilter());

        // 处理分页参数
        PageRequest pageRequest = processPageRequest(params.getPageRequest());

        // 确定区域类型
        IncomeQuestionService.AreaType areaType;
        String areaCode;

        if (StringUtils.hasText(params.getCityCode())) {
            areaType = IncomeQuestionService.AreaType.CITY;
            areaCode = params.getCityCode();
        } else {
            areaType = IncomeQuestionService.AreaType.PROVINCE;
            areaCode = params.getProvinceCode();
        }

        // 调用统一服务方法
        return incomeQuestionService.selectByOperation(
                operation.toUpperCase(),
                areaCode,
                areaType,
                condition,
                pageRequest
        );
    }
    @RequestMapping("/selectCollection")
    public List<IncomeQuestion> selectCollection() {
        return incomeQuestionService.selectCityCollection();
    }

    @GetMapping("/exportIncomeList")
    public ResponseEntity<ByteArrayResource> exportIncomeList(
            @RequestParam(value = "cityCode", required = false) String cityCode,
            @RequestParam(value = "provinceCode", required = false) String provinceCode,
            @RequestParam(value = "beginPreProjectDate", required = false) String beginPreProjectDate,
            @RequestParam(value = "endPreProjectDate", required = false) String endPreProjectDate) throws Exception {

        // 参数校验
        if ((cityCode == null && provinceCode == null) || (cityCode != null && provinceCode != null)) {
            throw new IllegalArgumentException("必须且只能传递 cityCode 或 provinceCode 中的一个参数");
        }

        // 创建条件对象并设置日期范围
        IncomeQuestion condition = new IncomeQuestion();
        condition.setBeginPreProjectDate(beginPreProjectDate);
        condition.setEndPreProjectDate(endPreProjectDate);

        List<IncomeQuestion> dataList;
        String fileName;

        if (cityCode != null) {
            dataList = incomeQuestionService.selectCityTotalIncomeAll(cityCode, condition);
            fileName = cityCode + "_项目明细.xlsx";
        } else {
            dataList = incomeQuestionService.selectProvinceTotalIncomeAll(provinceCode, condition);
            fileName = provinceCode + "_项目明细.xlsx";
        }

        // 对customerName字段进行Base64解密
        for (IncomeQuestion item : dataList) {
            if (item.getCustomerName() != null) {
                try {
                    item.setCustomerName(decodeBase64(item.getCustomerName()));
                } catch (Exception e) {
                    // 如果解密失败，保持原值并记录警告
                    logger.warn("customerName字段Base64解密失败: {}", item.getCustomerName());
                }
            }
        }

        // 生成Excel
        byte[] excelBytes = ExcelExportUtil.exportIncomeQuestionList(dataList);

        // 构建响应
        ByteArrayResource resource = new ByteArrayResource(excelBytes);
        ContentDisposition contentDisposition = ContentDisposition.attachment()
                .filename(fileName, StandardCharsets.UTF_8)
                .build();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(excelBytes.length)
                .body(resource);
    }

    /**
     * Base64解密方法
     */
    private String decodeBase64(String encodedString) {
        if (encodedString == null || encodedString.trim().isEmpty()) {
            return null;
        }
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
            return new String(decodedBytes, StandardCharsets.UTF_8);
        } catch (IllegalArgumentException e) {
            // 如果解密失败，可能是原始数据不是Base64编码，返回原值
            logger.warn("Base64解密失败，返回原值: {}", encodedString);
            return encodedString;
        }
    }

    private void validateParams(String cityCode, String provinceCode) {
        boolean hasCity = StringUtils.hasText(cityCode);
        boolean hasProvince = StringUtils.hasText(provinceCode);

        if (hasCity && hasProvince) {
            throw new IllegalArgumentException("城市与省份代码互斥");
        }
        if (!hasCity && !hasProvince) {
            throw new IllegalArgumentException("必须提供区域代码");
        }

        // 扩展校验规则
        if (hasCity && !cityCode.matches("\\d{5}")) {
            throw new IllegalArgumentException("城市代码需为5位数字");
        }
        if (hasProvince && !provinceCode.matches("\\d{5}")) {
            throw new IllegalArgumentException("省份代码需为5位数字");
        }
    }

}

